package com.mediacloud.app.newsmodule.activity

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.eventTrack.TXReportManager
import com.lidroid.xutils.HttpUtils
import com.lidroid.xutils.exception.HttpException
import com.lidroid.xutils.http.HttpHandler
import com.lidroid.xutils.http.ResponseInfo
import com.lidroid.xutils.http.callback.RequestCallBack
import com.mediacloud.app.assembly.util.FileUtil
import com.mediacloud.app.assembly.util.toast
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.CollectionController
import com.mediacloud.app.newsmodule.utils.CollectionController.CollectStatusListener
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.newsmodule.utils.load
import com.mediacloud.app.quanzi.model.AddBookReadBean
import com.mediacloud.app.quanzi.model.BaseDataBean
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.view.SimpleDialog
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.util.ClickUtils
import com.mediacloud.app.util.IOSTips
import com.mediacloud.appcloud.project.gxapp.model.utils.MD5Util
import com.model.EbookMode
import com.utils.CustomDrawable
import kotlinx.android.synthetic.main.activity_read_book.*
import kotlinx.android.synthetic.main.simple_title_bar_dark_tx.*
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File

class ReadBookInfoActivity : BaseBackActivity() {
    override fun getLayoutResID(): Int {
        return R.layout.activity_read_book
    }

    var ebookId: String? = null
    var handler: HttpHandler<File>? = null
    var eBook: EbookMode? = null
    var simpleDialog: SimpleDialog? = null
    var mTyReportStartTime: Long = 0
    var mTyReportEndTime: Long = 0
    var collectionController: CollectionController? = null
    var articleItem: ArticleItem? = null
    var isRead = false//标识是否进入了阅读页面
    var intoReadTime: Long = 0
    var types: ArrayList<String>? = null
    private var launchTimeLong = 0L
    override fun showTitleBar() = false

    override fun getStatusBarColor() = Color.WHITE

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ebookId = intent.getStringExtra("EBOOK_ID")
        types = intent.getStringArrayListExtra("EBOOK_TYPES")
        scrollView.background = CustomDrawable()
        simpleDialog = SimpleDialog(this)
        launchTimeLong = System.currentTimeMillis()
        backIv.setOnClickListener {
            finish()
        }
        val map: MutableMap<String, String> = HashMap()
        map["relaId"] = "$ebookId"
        map["type"] = "14"

        SpiderCmsApi.getSpiderCmsApi(this).addHitCount(map, getString(R.string.tenantid))
            .enqueue(object : Callback<BaseDataBean<AddBookReadBean>> {
                override fun onResponse(
                    call: Call<BaseDataBean<AddBookReadBean>>,
                    response: Response<BaseDataBean<AddBookReadBean>>
                ) {
                    val isSuccess = response.body()?.isSuccess
                    Log.e("AAA", "")
                    if (isSuccess == true){
                        readCountTv.text = "${response.body()?.data?.hitCount}"
                    }
                }

                override fun onFailure(call: Call<BaseDataBean<AddBookReadBean>>, t: Throwable) {
                    Log.e("AAA", "")
                }
            })

        SpiderCmsApi.getSpiderCmsApi(this).getEbookDetail("$ebookId", getString(R.string.tenantid))
            .enqueue(object : Callback<BaseDataBean<EbookMode>> {
                override fun onResponse(
                    call: Call<BaseDataBean<EbookMode>>,
                    response: Response<BaseDataBean<EbookMode>>
                ) {
                    val body = response.body() ?: return
                    if (body.isSuccess && body.data != null && !isFinish) {
                        val data = body.data
                        eBook = data
                        logoIv.load(
                            data.imagePath,
                            false,
                            AppFactoryGlobalConfig.getDefaultImageLoadDrawable()
                        )
                        titleTv2.text = data.title
                        titleTv.text = data.title
                        authorTv.text = data.author
                        scoreTv.text = "${data.score}"
                        contentLengthTv.text = "${data.wordNumber}万"
                        summaryTv.text = "${data.summary}"
                        mTyReportStartTime = System.currentTimeMillis()
                        mTyReportEndTime = mTyReportStartTime

                        articleItem = ArticleItem()
                        articleItem?.setAuthor(data?.author)
                        articleItem?.id = if (TextUtils.isEmpty(ebookId)) {
                            0L
                        } else {
                            try {
                                ebookId!!.toLong()
                            } catch (e: Exception) {
                                e.printStackTrace()
                                0L
                            }
                        }
                        if (types != null && types!!.size > 0) {
                            articleItem?.types = types
                        }
                        articleItem?.title = data?.title
                        articleItem?.summary = data?.summary
                        articleItem?.logo = data?.imagePath
                        articleItem?.hitCount = data?.hitCount?.toLong() ?: 0
                        articleItem?.type = TypeX.NEWS.BOOK
                        initCollect()

                    }else{
                        toast("无电子书信息")
                        finish()
                    }
                }

                override fun onFailure(call: Call<BaseDataBean<EbookMode>>, t: Throwable) {
                }
            })


        startReadTv.setOnClickListener {
            PermissionUtil.invokeStoragePermission(this, object : IPermissionsAgree {
                override fun onAgree() {
                    TXReportManager.getInstance()
                        .app_jhapp_content_detail_interact("开始阅读", "", "", articleItem,(System.currentTimeMillis()-launchTimeLong)/1000,"",null,null,null,null,null,null,null,null,null,null,null,null,null,null)
                    checkFile()
                }

                override fun onRefuse() {

                }

                override fun hasPermissions() {
                    checkFile()
                }
            })
        }
        tv_collect.setOnClickListener {
            ClickUtils.delayClickable(it)
            if (UserInfo.isLogin(this)) {
                if (CollectionController.isCollect(this, null, articleItem)) {
                    collectionController?.collection()
                } else {
                    IOSTips.showTips(this, "加入收藏", "喜欢这本书就加入收藏吧~\n可以在收藏中找到！",
                        object : IOSTips.IItem {
                            override val title: String = "取消"
                            override val color: Int = Color.parseColor("#969696")
                            override val click = View.OnClickListener {

                            }
                        },
                        object : IOSTips.IItem {
                            override val title: String = "确认"
                            override val color: Int =
                                ContextCompat.getColor(this@ReadBookInfoActivity, R.color.cctv7_red)
                            override val click = View.OnClickListener {
                                ClickUtils.delayClickable(it)
                                collectionController?.collection()

                            }
                        }
                    )
                }
            } else {
                LoginUtils.request_source=LoginUtils.source_collect;
                LoginUtils.invokeLogin(this)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkCollection()
    }

    fun checkCollection() {
        if (UserInfo.isLogin(this)) {
            collectionController?.checkCollection()
        } else {
            updateCollectUI(false)
        }
    }

    fun initCollect() {
        if (collectionController == null) {
            collectionController =
                CollectionController(
                    this@ReadBookInfoActivity,
                    null,
                    articleItem,
                    object : CollectStatusListener {
                        override fun onCollectionStatus(sourceId: String, collected: Boolean) {
                            updateCollectUI(collected)
                        }

                        override fun onCollectionOk(
                            sourceId: String,
                            collected: Boolean,
                            msg: String
                        ) {
                            updateCollectUI(collected)
                            if (collected) {
                                ToastUtil.showCollectToast(this@ReadBookInfoActivity, "已加入收藏")
                            } else {
                                ToastUtil.showToastCenter(this@ReadBookInfoActivity, msg)
                            }
                        }

                        override fun onCollectionErr(msg: String) {
                            ToastUtil.showToastCenter(this@ReadBookInfoActivity, msg)
                        }
                    })
            collectionController?.isShowToast = false
        }
        checkCollection()
    }

    fun updateCollectUI(collected: Boolean) {
        if (collected) {
            tv_collect.setText("已收藏")
            tv_collect.setCompoundDrawablesWithIntrinsicBounds(
                R.drawable.icon_ebook_collected,
                0,
                0,
                0
            )
        } else {
            tv_collect.setText("加入收藏")
            tv_collect.setCompoundDrawablesWithIntrinsicBounds(
                R.drawable.icon_ebook_un_collect,
                0,
                0,
                0
            )
        }
    }

    private fun checkFile() {
        val bookPath = eBook?.bookPath
        if (!TextUtils.isEmpty(bookPath)) {
            val directory = File(externalCacheDir, "ebook")
            if (!directory.exists()) {
                directory.mkdirs()
            }
            val fileName = MD5Util.MD5Encode(
                bookPath,
                "UTF-8"
            ) + bookPath!!.substring(bookPath.lastIndexOf("."));
            val file = File(directory, fileName)
            if (file.exists()) {
                val json = JSONObject()
                val array = JSONArray()
                array.put("${eBook?.imagePath}")
                json.put("epub_title", "${eBook?.title}")
                json.put("authorname", "${eBook?.author}")
                json.put("imgs", array)
                isRead = true
                intoReadTime = System.currentTimeMillis()
                /*FBReader.openBookActivity(
                    this@ReadBookInfoActivity,
                    file.absolutePath,
                    eBook?.id ?: 0,
                    true
                )
                DataManager.getINSTANCE().curBookNetId = eBook?.id ?: 0
                DataManager.getINSTANCE().curNetBook = json.toString()*/

            } else {
                val tempDirectory = File(externalCacheDir, "temp_ebook")
                if (!tempDirectory.exists()) {
                    tempDirectory.mkdirs()
                }
                val tempFile = File(tempDirectory, fileName)
                if (tempFile.exists()) {
                    tempFile.delete()
                }
                simpleDialog?.updateText("正在下载...")
                simpleDialog?.show()
                down(bookPath, tempFile, file)
            }
        } else {
            toast("未配置书本信息")
        }
    }

    private fun down(bookPath: String, temp: File, dst: File) {
        val http = HttpUtils()
        handler = http.download(
            bookPath,
            temp.absolutePath,
            true,
            false,
            object : RequestCallBack<File>() {
                override fun onSuccess(responseInfo: ResponseInfo<File>?) {
                    simpleDialog?.dismiss()
                    FileUtil.copyFile(dst.absolutePath, temp.absolutePath)
                    if (temp.exists()) {
                        temp.delete()
                    }
                    checkFile()
                }

                override fun onFailure(error: HttpException?, msg: String?) {
                    simpleDialog?.dismiss()
                    if (temp.exists()) {
                        temp.delete()
                    }
                    toast("网络异常，请检查网络")
                }
            })
    }

    override fun finish() {
        super.finish()
        if (eBook != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler?.cancel()
    }
}